package session;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.Query;

import entity.FootballMatch;
import entity.Players;

@Stateless
@Remote(FootballMatchDao.class)
public class FootballMatchDaoBean extends GenericDaoBean<FootballMatch, Integer>  implements FootballMatchDao{

	@EJB
	private PlayersDao playersDao;
	
	@Override
	public FootballMatch getActive() {
		try{
			Query q = em.createQuery("SELECT f FROM FootballMatch f WHERE f.votingActive=true");
			return (FootballMatch)q.getSingleResult();
		}catch(Exception e){
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Boolean deactivateAll() {
		try{
			Query q = em.createQuery("SELECT f FROM FootballMatch f WHERE f.votingActive=true");
			List<FootballMatch> matchList = q.getResultList();
			for(FootballMatch fm:matchList){
				fm.setVotingActive(false);
				
				List<Players> players = playersDao.findMvpByAppointment(fm.getAppointment());
				if(players!=null) {
					fm.setMvp(players.get(0).getUser());
					if(players.size()>1) {
						if(players.get(0).getMvp().equals(players.get(1).getMvp()) ) {
							if (players.get(0).getGoal().equals(players.get(1).getGoal())) {
								fm.setMvp(null);
							}
						}
					}
					
				}
				persist(fm);
			}
			return true;
		}catch(Exception e){
			return false;
		}
	}

}
